﻿@{
    ViewBag.Title = "Form";
    Layout = "~/Views/Shared/_Form.cshtml";
}
<script>
    var keyValue = $.request("keyValue");
    var sitename = $.request("sitename");
    var siteId = $.request("siteId");
    var id = $.request("id");
    var photoList = [], photoListDel = [], Spacedata = [], videoList = [], videoListDel = [];
    $(function () {
        $("#F_SiteId").val(siteId);
        getSpaceList();
        gridSpaceList();
        var ActivityType = top.frames["iframe" + id].ActivityType;
        if (ActivityType) {
            for (var i = 0; i < ActivityType.length; i++) {
                $("#F_ActivitiesType").append("<option value='" + ActivityType[i].F_ItemCode + "'>" + ActivityType[i].F_ItemName + "</option>");
            }
        }

        $("#F_ActivitiesType").bindSelect();
        $("#F_SpaceId").bindSelect();
        if (!!keyValue) {
            $.ajax({
                url: "/SiteManage/ActivitiesCase/GetFormJson",
                data: { keyValue: keyValue },
                dataType: "json",
                async: false,
                success: function (data) {
                    $("#form1").formSerialize(data.activitiesCaseEntity);
                    photoList = data.photosList;
                    videoList = data.VideoList;
                    getPhotoListHtml();
                    getVideoListHtml();
                }
            });
        }
        $("#PhotoFile").change(function () {
            $("#displaydiv").empty();
            for (var i = 0, j = this.files.length; i < j; i++) {
                $("#displaydiv").append("<img name='" + this.files[i].name + "' src=\"" + window.URL.createObjectURL(this.files[i]) + "\">");
            }
        });

    });
    function getSpaceList() {
        $.ajax({
            url: "/SiteManage/Space/GetListBySiteId",
            dataType: "json",
            data: { F_SiteId: siteId },
            async: false,
            success: function (data) {
                Spacedata = data;
            }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(XMLHttpRequest);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    }
    function gridSpaceList() {
        var data = Spacedata;
        $("#F_SpaceId").empty();
        for (var i = 0; i < data.length; i++) {
            $("#F_SpaceId").append("<option value='" + data[i].F_Id + "'>" + data[i].title + "</option>");
        }
        $("#F_SpaceId").bindSelect()//所属空间
    }
    function submitForm() {
        if (!$('#form1').formValid()) {
            return false;
        }
        if (photoList.length >= 3 && photoList.length < 11) {

            var PhotoAndFileList = [];
            PhotoAndFileList = photoList;
            rdioIs_Cover();
            checkF_IsEmphasis();

            VideoIs_Cover();
            if (!is_ThereCover) {
                $.modalAlert("请先设置显示首图！", "warning");
                return false;
            }
            if (is_ThereEmphasis != 3) {
                $.modalAlert("请先设置重点图三张！", "warning");
                return false;
            }
            //需要从数据库删除的图片数据
            for (var i = 0; i < photoListDel.length; i++) {
                PhotoAndFileList.push(photoListDel[i]);
            }

            //需要更新或修改的视频数据
            for (var i = 0; i < videoList.length; i++) {
                PhotoAndFileList.push(videoList[i]);
            }
            //需要从数据库删除的视频数据
            for (var i = 0; i < videoListDel.length; i++) {
                PhotoAndFileList.push(videoListDel[i]);
            }
            var params = {
                activitiesCaseOutput: JSON.stringify({
                    activitiesCaseEntity: $("#form1").formSerialize(),
                    photosList: PhotoAndFileList//图片
                })
            };
            //$.submitForm({
            //    url: "/SiteManage/ActivitiesCase/SubmitForm?keyValue=" + keyValue,
            //    param: params,
            //    success: function () {
            //        if (id.length > 12) {
            //            id = "iframe" + id;
            //            top.frames[id].window.$("#ActivitiesgridList").trigger("reloadGrid");
            //            $.modalFrameClose(window.name);
            //        } else {
            //            $.currentWindow().$("#ActivitiesgridList").trigger("reloadGrid");
            //            $.modalFrameClose(window.name);
            //        }
            //    }
            //})

            $.ajax({
                url: "/SiteManage/ActivitiesCase/SubmitForm?keyValue=" + keyValue,
                dataType: "json",
                type: 'post',
                data: params,
                async: false,
                success: function (data) {
                    if (data.state == "success") {
                        $.modalAlert("活动案例信息提交成功!", "warning");
                        if (id.length > 12) {
                            id = "iframe" + id;
                            top.frames[id].window.$("#ActivitiesgridList").trigger("reloadGrid");
                            $.modalFrameClose(window.name);
                        } else {
                            $.currentWindow().$("#ActivitiesgridList").trigger("reloadGrid");
                            $.modalFrameClose(window.name);
                        }
                    } else {
                        $.modalAlert("信息提交失败，请联系管理员!", "warning");
                    }
                }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });

        }
        else {
            $.modalAlert("图片请控制3-10张哦!", "warning");
        }
    }
    var h = "http://storage.yunspace.com.cn/";


    //动态获取小视频HTML
    function getVideoListHtml() {
        $("#VideoList").empty();
        for (var i = 0; i < videoList.length; i++) {
            var cha = "", is_Emphasis = "";
            if (videoList[i].is_cover) {
                cha = "checked";
            }
            var url = "";
            url = h + videoList[i].F_path + "?v=" + RndNum(14);
            $("#VideoList").append("<div class='video'><video style= 'width:150px; height:220px;' src='" + url + "' controls preload='auto'></video ><div><input type='text' id='"
                + videoList[i].F_Id + "' class='form-control videotag' onChange=\"uptag('" + videoList[i].F_Id + "', this.value,videoList)\" value='" + videoList[i].tag
                + "' placeholder='参考：活动视频/搭建视频' /><input type='radio' class='rdio' " + cha + " id='radio" + videoList[i].F_Id
                + "' name='videois_cover' value='" + videoList[i].F_Id + "' />优选<a class='photodel' onclick=\"btn_delete_files('"
                + videoList[i].F_Id + "','ActivitiesCaseVideo')\">删除</a></div></div >");
        }
    }

    //动态获取图片HTML
    function getPhotoListHtml() {
        $("#photoList").empty();
        for (var i = 0, j = photoList.length; i < j; i++) {
            var cha = "", is_Emphasis = "";
            if (photoList[i].is_cover) {
                cha = "checked";
            }
            if (photoList[i].F_IsEmphasis) {
                is_Emphasis = "checked";
            }
            var url = "";
            url = h + photoList[i].F_path + "?" + Math.random();
            $("#photoList").append("<div class='imgList'><img id='img" + photoList[i].F_Id
                + "' style= 'width:120px; height:100px;' /><div><input type='radio' class='rdio' " + cha + " id='radio" + photoList[i].F_Id
                + "' name='is_cover' value='" + photoList[i].F_Id + "' />首图<a class='photodel' onclick=\"btn_delete_files('"
                + photoList[i].F_Id + "','photoList')\">删除</a><br><input type='checkbox' " + is_Emphasis + " id='checkbox" + photoList[i].F_Id
                + "' name='is_Emphasis' value='" + photoList[i].F_Id + "' />重点</div></div >");
            $("#img" + photoList[i].F_Id).attr('src', src = url);
        }
    }

    function checkDownload(id) {
        document.getElementById("Down" + id).checked = document.getElementById("Down" + id).checked ? false : true;
    }

    function downloadImage(src) {
        var $a = $("<a></a>").attr("href", src).attr("download", "meitu.png");
        $a[0].click();
    }
    var is_Down = 0;
    //获取需要下载的图片
    function checkIsDown() {
        if (photoList.length > 0) {
            var $selectedvalue = $("input[name='isDownload']");
            for (var i = 0; i < photoList.length; i++) {
                if ($selectedvalue[i].checked && i == $selectedvalue[i].value) {
                    is_Down += 1;
                    downloadImage(h + photoList[i].F_path);
                }
            }
        } else {
            $.modalAlert("请先上传场地图片!", "warning");
        }
        if (is_Down == 0) {
            $.modalAlert("请先点击图片选择您要下载的项目!", "warning");
        }
    }

    var is_ThereCover = false;
    var is_ThereEmphasis = 0;
    //获取首图
    function rdioIs_Cover() {
        if (photoList.length > 0) {
            var $selectedvalue = $("input[name='is_cover']:checked").val();
            $selectedvalue = $selectedvalue == undefined ? "" : $selectedvalue;
            for (var i = 0; i < photoList.length; i++) {
                if (photoList[i].F_Id == $selectedvalue) {
                    is_ThereCover = true;
                    photoList[i].is_cover = true;
                }
                else {
                    photoList[i].is_cover = false;
                }
            }
        }
    }
    //是否重点图片
    function checkF_IsEmphasis() {
        is_ThereEmphasis = 0;
        if (photoList.length > 0) {
            var $selectedvalue = $("input[name='is_Emphasis']");
            for (var i = 0; i < photoList.length; i++) {
                if ($selectedvalue[i].checked && photoList[i].F_Id == $selectedvalue[i].value) {
                    is_ThereEmphasis += 1;
                    photoList[i].F_IsEmphasis = true;
                }
                else {
                    photoList[i].F_IsEmphasis = false;
                }
            }
        }
    }
    //获取优选视频
    function VideoIs_Cover() {
        if (videoList.length > 0) {
            var $selectedvalue = $("input[name='videois_cover']:checked").val();
            $selectedvalue = $selectedvalue == undefined ? "" : $selectedvalue;
            for (var i = 0; i < videoList.length; i++) {
                if (videoList[i].F_Id == $selectedvalue) {
                    videois_ThereCover = true;
                    videoList[i].is_cover = true;
                }
                else {
                    videoList[i].is_cover = false;
                }
            }
        }
    }
    
    //修改图片tag
    function uptag(F_Id, value, list) {
        for (var i = 0; i < list.length; i++) {
            if (list[i].F_Id == F_Id) {
                list[i].tag = value;
                break;
            }
        }
    }

    //删除单个资料文件
    function btn_delete_files(F_Id, type) {
        if ($("#F_ActivitiesTitle").val()) {
            if (type == "ActivitiesCaseVideo") {
                VideoIs_Cover();
                $("#VideoList").empty();
                if (videoList.length > 0) {
                    for (var i = 0; i < videoList.length; i++) {
                        if (videoList[i].F_Id == F_Id) {
                            if (videoList[i].F_Id.length > 4) {
                                videoList[i].F_DeleteMark = true;
                                videoListDel.push(videoList[i])
                            }
                            RemoveValByIndex(videoList, i);
                        }
                    }
                    getVideoListHtml();
                }
            } else {
                $("#photoList").empty();
                if (photoList.length > 0) {
                    for (var i = 0; i < photoList.length; i++) {
                        if (photoList[i].F_Id == F_Id) {
                            if (photoList[i].F_Id.length > 4) {
                                photoList[i].F_DeleteMark = true;
                                photoListDel.push(photoList[i]);
                            }
                            RemoveValByIndex(photoList, i);
                        }
                    }
                    getPhotoListHtml();
                }
            }
        }
        else {
            $.modalAlert("请先填写活动案例数据！", "warning");
        }
    }
    var xhr;
    var cvalue = "";
    var bigvlue = "",imgWidthType = "";
    //批量上传资料文件
    function uploadSend(actionId, type) {
        cvalue = "";
        bigvlue = "";
        imgWidthType = "";
        if ($("#F_ActivitiesTitle").val()) {
            var data = new FormData();
            var item = document.getElementById(actionId);
            if (item != null && item.files.length > 0) {
                var files = item.files;
                if (type == "ActivitiesCaseVideo") {
                    var fid = videoList == null ? 0 : videoList.length;
                    videoList = videoList == null ? [] : videoList;
                    bigvlue = "";
                    for (var i = 0; i < files.length; i++) {
                        var file = item.files[i];
                        fileSize = file.size;
                        fileSize = Math.round(fileSize / 1024 * 100) / 100; //kb
                        if (fileSize > 10240) {
                            bigvlue += file.name + ' ';
                        } else {
                            data.append(file.name, file);
                            videoList.push({
                                name: file.name,
                                F_Id: fid + i,
                                tag: '',
                                is_cover: false,
                                F_IsEmphasis: false,
                                photoable_type: type,
                                F_path: "uploads/files/path/Activities/" + file.name
                            });
                        }
                    }
                } else {
                    var fid = photoList.length;
                    for (var i = 0; i < files.length; i++) {
                        var file = item.files[i];
                        fileSize = file.size;
                        fileSize = Math.round(fileSize / 1024 * 100) / 100; //kb
                        if (createReader(i)) {
                            if (fileSize > 10240) {
                                bigvlue += file.name + ' ';
                            } else {
                                data.append(file.name, file);
                                photoList.push({
                                    name: file.name,
                                    F_Id: fid + i,
                                    tag: '',
                                    is_cover: false,
                                    photoable_type: type,
                                    F_path: 'uploads/files/path/Activities/' + file.name
                                })
                            }
                        }
                    }
                }


                $.loading(true, "文件正在上传中，请稍后...");
                xhr = new XMLHttpRequest();
                xhr.onload = function () {
                    data = JSON.parse(xhr.responseText);
                    if (data.state == 1) {
                        if (imgWidthType != "") {
                            $.modalAlert(imgWidthType, "warning");
                        }
                        else if (cvalue != "" && bigvlue != "") {
                            $.modalAlert(cvalue + "图片比例不对，请提供长宽比为4:3的常规横向展示照片，最小尺寸（790*526）," + bigvlue + "超过了限制大小,请上传" + big + "MB内的文件", "warning");
                        }
                        else if (bigvlue != "") {
                            $.modalAlert(bigvlue + "超过了限制大小,请上传" + big + "MB内的文件", "warning");
                        }
                        else if (cvalue != "") {
                            $.modalAlert(cvalue + "图片比例不对，请提供长宽比为4:3的常规横向展示照片", "warning");
                        } else {
                            $.modalAlert("资料保存成功!", "warning");
                        }
                        var file = document.getElementById(actionId);
                        file.value = "";
                    } else {
                        if (imgWidthType != "") {
                            $.modalAlert(imgWidthType, "warning");
                        }
                        else if (cvalue != "" && bigvlue != "") {
                            $.modalAlert(cvalue + "图片比例不对，请提供长宽比为4:3的常规横向展示照片，最小尺寸（790*526）," + bigvlue + "超过了限制大小,请上传" + big + "MB内的文件", "warning");
                        }
                        else if (bigvlue != "") {
                            $.modalAlert(bigvlue + "超过了限制大小,请上传" + big + "MB内的文件", "warning");
                        }
                        else if (cvalue != "") {
                            $.modalAlert(cvalue + "图片比例不对，请提供长宽比为4:3的常规横向展示照片", "warning");
                        } else {
                            $.modalAlert("上传失败！", "warning");
                        }
                        $.loading(false, "");
                    }
                    if (type == "ActivitiesCaseVideo") {
                        getVideoListHtml();
                    } else {
                        getPhotoListHtml();
                    }
                    $.loading(false, "");
                };
                xhr.onerror = function (err) {
                    console.error(err);
                    $.loading(false, "");
                };
                xhr.open('post', '/SiteManage/Site/UploadPathFiles?sitename=Activities&type=ActivitiesCase', true);
                xhr.send(data);
            }
            else {
                $.modalAlert("请先选择您要上传的文件！", "warning");
            }
        }
        else {
            $.modalAlert("请先填写活动案例数据！", "warning");
        }
    }
    function createReader(i) {
        var divs = document.getElementById("displaydiv");
        var imgs = divs.getElementsByTagName("img");
        if (imgs.length > 0) {
            var w = imgs[i].width;
            var h = imgs[i].height;
            if (w < h) {
                imgWidthType += imgs[i].name + "图片比例不正确";
                return false;
            }
            else if (w < 790 || h < 526) {
                imgWidthType += imgs[i].name + "图片过小,最小尺寸（790*526）";
                return false;
            }
            else {
                return true;
            }
        }
    }
</script>

<style>
    .photodel {
        margin-left: 40px;
        color: red;
    }

    .imgtag {
        width: 95px !important;
        height: 10px !important;
        text-align: center;
        margin-top: 10px;
        margin-bottom: 5px;
    }

    #photoList {
        margin-left: 40px;
        height: 190px;
    }

        #photoList .imglink {
            position: relative;
            cursor: pointer;
            height: 100px;
            width: 120px;
        }


    .isDownload {
        position: absolute;
        right: 5px;
        top: 5px;
    }

    .imgList {
        float: left;
        width: 120px;
        height: 150px;
        margin: 10px;
        text-align: left;
    }

    .video {
        float: left;
        width: 150px;
        height: 260px;
        margin: 10px;
        text-align: left;
    }
</style>
<form id="form1">
    <div style="padding-top: 20px; margin-right: 20px;">
        <table class="form">
            <tr>
                <th class="formTitle">所属空间<span style="color:red">*</span></th>
                <td class="formValue">
                    <input id="F_SiteId" name="F_SiteId" type="hidden" />
                    <select id="F_SpaceId" name="F_SpaceId" class="form-control required">
                        <option value="">==请录入空间编号==</option>
                    </select>
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">活动名称<span style="color:red">*</span></th>
                <td class="formValue">
                    <input id="F_ActivitiesTitle" name="F_ActivitiesTitle" type="text" maxlength="100" class="form-control required" placeholder="请录入活动名称 50字以内" />
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">活动类型<span style="color:red">*</span></th>
                <td class="formValue">
                    <select id="F_ActivitiesType" name="F_ActivitiesType" class="form-control required">
                        <option value="">==请录入活动类型==</option>
                    </select>
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">活动人数<span style="color:red">*</span></th>
                <td class="formValue">
                    <input id="F_ActivitiesNumber" name="F_ActivitiesNumber" type="text" maxlength="30" class="form-control required" placeholder="请录入活动人数" />
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">活动开始时间</th>
                <td class="formValue">
                    <input id="F_StarDate" name="F_StarDate" type="text" class="form-control" maxlength="100" placeholder="请录入活动开始时间" />
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">活动结束时间</th>
                <td class="formValue">
                    <input id="F_EndDate" name="F_EndDate" type="text" class="form-control" maxlength="100" placeholder="请录入活动结束时间" />
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">活动描述<span style="color:red">*</span></th>
                <td class="formValue">
                    <textarea id="F_ActivityDesc" name="F_ActivityDesc" class="form-control required" maxlength="2000" style="height:100px" placeholder="参考填写：世界领先的运动品牌阿迪达斯跑步在成都春熙路步行街，展开为期两天的全新阿迪达斯“无处不清风”360度透气酷跑路演。阿迪达斯climacool清风系列跑鞋承袭2012年成功之势，为消费者带来“无处不清风”360度透气酷跑的最新体验活动，让到场消费者可以尽情试穿climacool清风系列的各款跑鞋，并通过30秒新奇“抓冰”或自备“武器”加入破冰大战，勇夺最新款climacool清风跑鞋。"></textarea>
                </td>
                <td></td>
            </tr>
            <tr>
                <th class="formTitle">图片上传（支持批量上传）</th>
                <td class="formValue">
                    <input id="PhotoFile" accept="image/*" class="form-control" type="file" name="filesf" multiple />
                </td>
                <td style="width:80px;">
                    <input id="F_FilesBtn" onclick="uploadSend('PhotoFile','ActivitiesCase')" type="button" value="上传图片" class="btn btn-primary" />
                </td>
            </tr>
            <tr>
                <td colspan="3" id="pList">
                    <div id="photoList" style="height:190px;">
                    </div>
                </td>
                <td width="200">
                    <div id="displaydiv" style="display:none"></div>
                    <p><span style="color:forestgreen">提示：</span> 此处需要您上传3-10张活动现场照片，为保证您所上传的图片资料给到客户更好的展示效果， 请提供长宽比为4:3的常规横向展示照片，最小尺寸（790*526），如上传的图片不符合这一要求，我们将会默认裁剪为适合的显示比例。 图片要求清晰，单张最大不超过10MB</p>
                </td>
            </tr>
            <tr>
                <th class="formTitle">活动小视频（支持多选批量上传）</th>
                <td class="formValue">
                    <input id="CaseVideoFile" class="form-control" accept="video/*" type="file" name="CaseVideoFile" multiple />
                </td>
                <td>
                    <input id="F_VideoFilesBtn" onclick="uploadSend('CaseVideoFile','ActivitiesCaseVideo')" type="button" value="上传视频" class="btn btn-primary" />
                </td>
                <td>
                    <p>
                        <span style="color:forestgreen">提示：</span>此处可以上传一些有关场地的活动小视频，有助于客户更直观地了解您的场地，单个文件大小请控制在10MB以内
                    </p>
                </td>
            </tr>
            <tr>
                <th></th>
                <td class="formValue" colspan="3">
                    <div id="VideoList">
                    </div>
                </td>
            </tr>
        </table>
    </div>
</form>


